<script setup lang='ts'>
import { useInventoryHistoryCascade, useInventoryHistoryExport, useInventoryHistoryIndex } from '@fl/api/add-elevator-api/inventory-history'
import { SearchForm, SearchTable } from '@fl/components'
import { treeFindLabel } from '@fl/utils/tree'
import dayjs from 'dayjs'
import { cloneDeep } from 'lodash-es'
import type { OptionsType, PlusColumn } from 'plus-pro-components'

import { AUTH_RESULT, AUTH_RESULT_OPTIONS, VERIFY_STATUS_OPTIONS } from '../requirement/constant'
import VerifyResult from './components/detail.vue'

defineOptions({
    // eslint-disable-next-line vue/component-definition-name-casing
    name: 'retrofit-elevator-inventory-history',
})
const projectCode = ref('')

const showDetail = ref<boolean>(false)
const detailData = ref<any>()
const initialState = {} as any
const state = ref(cloneDeep(initialState))
const searchConditions = ref(cloneDeep(initialState))

const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})

const getAreaOptionsParams = computed(() => ({
    targetLabel: 'area',
}))
const getStreetOptionsParams = computed(() => ({
    areaCode: state.value.areaCode,
    targetLabel: 'street',
}))
const getCommunityOptionsParams = computed(() => ({
    streetCode: state.value.streetCode,
    targetLabel: 'community',
}))
const getProjectOptionsParams = computed(() => ({
    communityCode: state.value.communityCode,
    areaCode: state.value.areaCode,
    streetCode: state.value.streetCode,
    targetLabel: 'project',
    projectCode: projectCode.value,
}))
const getBuildingOptionsParams = computed(() => ({
    projectId: state.value.projectId,
    targetLabel: 'building',
}))
const getUnitOptionsParams = computed(() => ({
    building: state.value.building,
    targetLabel: 'unit',
}))
const getVerifyFailPageParams = computed(() => ({
    ...searchConditions.value,
    endTime: searchConditions.value.submitTimeRange?.[1],
    pageIndex: tablePage.currentPage,
    pageSize: tablePage.pageSize,
    startTime: searchConditions.value.submitTimeRange?.[0],
}))

const { data: areaOptions } = useInventoryHistoryCascade(getAreaOptionsParams)
const { data: streetOptions } = useInventoryHistoryCascade(getStreetOptionsParams, 'areaCode')
const { data: communityOptions } = useInventoryHistoryCascade(getCommunityOptionsParams, 'streetCode')
const { data: projectOptions,isLoading:projectLoading } = useInventoryHistoryCascade(
    getProjectOptionsParams,
    'projectCode'
)
const { data: buildingOptions } = useInventoryHistoryCascade(getBuildingOptionsParams, 'projectId')
const { data: unitOptions } = useInventoryHistoryCascade(getUnitOptionsParams, 'building')
const { data: verifyFailPageData, isLoading: isGetVerifyFailPageLoading } = useInventoryHistoryIndex(getVerifyFailPageParams)
function projectSearch(keyword){
    projectCode.value = keyword
}
const isFormLoading = computed(() => false)

// 导出
const exportParams = computed(() => ({
    // ...searchConditions.value,
    areaCode: searchConditions.value.areaCode,
    streetCode: searchConditions.value.streetCode,
    communityCode: searchConditions.value.communityCode,
    projectId: searchConditions.value.projectId,
    building: searchConditions.value.building,
    unit: searchConditions.value.unit,
    ownerName: searchConditions.value.ownerName,
    status: searchConditions.value.status,
    auth: searchConditions.value.auth,
    endTime: searchConditions.value.submitTimeRange?.[1],
    startTime: searchConditions.value.submitTimeRange?.[0],
}))
const { isPending, mutateAsync } = useInventoryHistoryExport(exportParams)
async function exportData() {
    const res = await mutateAsync()
    if (res) {
        const objectUrl = URL.createObjectURL(res)
        location.href = objectUrl
        URL.revokeObjectURL(objectUrl)
    }
}

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true
        },
        label: '所在区',
        options: areaOptions as OptionsType,
        prop: 'areaCode',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true
        },
        label: '街道',
        options: streetOptions as OptionsType,
        prop: 'streetCode',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true
        },
        label: '社区',
        options: communityOptions as OptionsType,
        prop: 'communityCode',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
       // fieldProps: {
        //     filterable: true,
        // },
        label: '小区',
        // options: projectOptions as OptionsType,
        prop: 'projectId',
        // valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true
        },
        label: '栋',
        options: buildingOptions as OptionsType,
        prop: 'building',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true
        },
        label: '单元',
        options: unitOptions as OptionsType,
        prop: 'unit',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        label: '业主信息',
        prop: 'ownerName',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 8,
        },
        fieldProps: {
            endPlaceholder: '请选择结束时间',
            startPlaceholder: '请选择开始时间',
            type: 'datetimerange',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            'disabled-date': (time: Date) => {
                            return dayjs(time).isAfter(dayjs(new Date()).format('YYYY-MM-DD 23:59:59'))
                        },
        },
        label: '提交时间',
        prop: 'submitTimeRange',
        valueType: 'date-picker',

    },
]

function submit() {
    searchConditions.value = cloneDeep(state.value)
    resetTablePage()
}

function reset() {
    state.value = cloneDeep(initialState)
    searchConditions.value = cloneDeep(initialState)
    resetTablePage()
}

function resetTablePage() {
    tablePage.currentPage = 1
    tablePage.pageSize = 10
}

watch(() => state.value.areaCode, () => {
    const { building, communityCode, projectId, streetCode, unit, ...data } = state.value
    state.value = cloneDeep(data)
})

watch(() => state.value.streetCode, () => {
    const { building, communityCode, projectId, unit, ...data } = state.value
    state.value = cloneDeep(data)
})

watch(() => state.value.communityCode, () => {
    const { building, projectId, unit, ...data } = state.value
    state.value = cloneDeep(data)
})

watch(() => state.value.projectId, () => {
    const { building, unit, ...data } = state.value
    state.value = cloneDeep(data)
})

watch(() => state.value.building, () => {
    const { unit, ...data } = state.value
    state.value = cloneDeep(data)
})

const isTableLoading = computed(() => isGetVerifyFailPageLoading.value)
const tableData = ref<any[]>([])

const gridOptions = reactive({
    columns: [
        { field: 'applyNo', title: '编号', width: 240 },
        { field: 'areaName', title: '所在区', width: 100 },
        { field: 'streetName', title: '街道', width: 100 },
        { field: 'communityName', title: '社区', width: 100 },
        { field: 'projectName', title: '小区', width: 100 },
        { field: 'buildingAndUnit', slots: { default: 'building_and_unit' }, title: '栋-单元', width: 100 },
        { field: 'applicantMobile', title: '上报人账号', width: 120 },
        { field: 'ownerName', title: '业主姓名', width: 80 },
        { field: 'ownerIdCard', title: '业主身份证号', width: 200 },
        { field: 'houseAddr', title: '详细地址', width: 200 },
        { field: 'auth', slots: { default: 'auth' }, title: '身份初步对比结果', width: 80 },
        { field: 'status', slots: { default: 'status' }, title: '身份核实状态', width: 110 },
        { field: 'createTime', title: '提交时间', width: 170 },
        { fixed: 'right', slots: { default: 'operation' }, title: '操作', width: 140 },
    ],
})


function onDetailBtnClick(row: any) {
    detailData.value = row
    showDetail.value = true
}

watchEffect(() => {
    if(verifyFailPageData.value) {
        tableData.value = cloneDeep(verifyFailPageData.value.records)
        tablePage.total = verifyFailPageData.value.total
    }
    
})
</script>

<template>
    <el-card mb-20
             shadow="never"
    >
        <el-skeleton v-if="isFormLoading"
                     animated
        />

        <SearchForm v-else
                    v-model="state"
                    :columns="columns"
                    submit-text="查询"
                    :row-props="{ gutter: 40 }"
                    @submit="submit"
                    @reset="reset"
        >
        <template #plus-field-projectId>
        <el-select
        v-model="state.projectId"
        filterable
        remote
        reserve-keyword
        placeholder="请输入小区名称"
        remote-show-suffix
        :remote-method="projectSearch"
        :loading="projectLoading"
      >
        <el-option
          v-for="item in projectOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
       </template>
       </SearchForm>
    </el-card>

    <el-card shadow="never">
        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isTableLoading"
                     :data="tableData"
        >
            <template #toolbar_buttons>
                <div class="mb-12 flex w-full justify-between">
                    <div>
                        <el-button type="primary"
                                    @click="exportData"
                                    :loading="isPending"
                        >
                            <div class="i-iconamoon:upload size-16" />
                            导出
                        </el-button>
                    </div>
                </div>
            </template>

            <template #building_and_unit="{ row }">
                <span>{{ `${row.building}${row.unit === '无' ? '' : `-${row.unit}`}` }}</span>
            </template>

            <template #auth="{ row }">
                <span>{{ treeFindLabel({ targetValue: row.auth, treeData: AUTH_RESULT_OPTIONS }) }}</span>
            </template>

            <template #status="{ row }">
                <!-- 身份初步比对结果=不在清册范围内时，身份核实状态应该显示为/ -->
                <span v-if="row.auth === AUTH_RESULT.ERROR">/</span>
                <span v-else>{{ treeFindLabel({ targetValue: row.status, treeData: VERIFY_STATUS_OPTIONS }) }}</span>
            </template>

            <template #operation="{ row }">
                <el-button class="!p-4"
                           text
                           @click="onDetailBtnClick(row)"
                >
                    详情
                </el-button>
            </template>
        </SearchTable>
    </el-card>

    <VerifyResult v-model:visible="showDetail"
                  :data="detailData"
    />

</template>
